import React, { useState, useEffect } from 'react';
import styles from './step1.less';
import step1Img from '../../assets/login/step1H.png';
import completed from '../../assets/login/completed.png';
import { useForm } from 'react-hook-form';
import phoneIcon from '../../assets/enquiry/phone.png';
import peopleIcon from '../../assets/enquiry/people.png';
import { useDispatch, useSelector } from 'dva';
import { Toast, Popup } from 'antd-mobile';
import { useIntl, getLocale } from 'umi';

import { checkEmailIsExist } from '../../servers/index';

// import {apiGetSmsCode} from '../../servers'
let time = null;
function Step1({ onNext }) {
  let phoneReg = /^1[0-9]{10}$/;
  const {
    register,
    setValue,
    handleSubmit,
    formState: { errors },
  } = useForm();
  const { loginTypeIndex } = useSelector(({ index }) => index);

  const [focusIndex, setFocusIndex] = useState(1);
  const dispatch = useDispatch();
  const [index, setIndex] = useState();
  const [isWait, setIsWait] = useState(false);
  // const [tabIndex, setTabIndex] = useState(0);
  const [loginType, setLoginType] = useState(1);
  const [email, setEmail] = useState();
  const [emailIsExist, setEmailIsExist] = useState(true);

  let tabs = [
    { name: '展商登录', nameEn: 'Exhibition' },
    { name: '观众登录', nameEn: 'Visitor' },
  ];

  const onChange = (i) => {
    setTabIndex(i);
  };

  function getSmsCode(data) {
    // console.log(data, 'dddddddd')

    if (!phoneReg.test(data.phone)) {
      Toast.fail(intl.formatMessage({ id: 'PLEASE_ENTER_THE_CORRECT_PHONE_NUMBER' }), 2);
      return;
    }

    if (isWait) {
      return;
    }
    dispatch({
      type: 'index/apiGetSmsCode',
      payload: {
        number: data.phone,
      },
      callback: (status) => {
        if (status) {
          setIsWait(true);
        } else {
          Toast.fail(intl.formatMessage({ id: 'ERROR_OBTAINING' }));
        }
      },
    });
  }
  function onSubmit(data) {
    // console.log(data, 'dddddddd',errors)
    if (loginType === 1) {
      if (loginTypeIndex === 0) {
        dispatch({
          type: 'index/apiExhibitorLogin',
          payload: {
            userName: data.userName,
            password: data.password,
          },
          callback: (status) => {
            if (status) {
              onNext();
            } else {
              Toast.fail(intl.formatMessage({ id: 'USERNAME_OR_PASSWORD_IS_INCORRECT' }));
            }
          },
        });
      } else {
        dispatch({
          type: 'index/apiLogin',
          payload: {
            phoneNumber: data.phone,
            code: data.code,
            type: 'PHONE_CODE',
          },
          callback: (status) => {
            if (status) {
              if (time != null) {
                clearInterval(time);
                setIsWait(false);
                time = null;
              }
              onNext();
            } else {
              Toast.fail(intl.formatMessage({ id: 'PHONE_NUMBER_OR_VERIFICATION_IS_INCORRECT' }));
            }
          },
        });
      }
    } else {
      if (!emailIsExist && data.password !== data.rePassword) {
        Toast.fail(intl.formatMessage({ id: 'REPASSWORD_IS_INCORRECT' }));
        return;
      }
      dispatch({
        type: 'index/apiLogin',
        payload: {
          email: data.email,
          password: data.password,
          type: 'EMAIL_PASSWORD',
        },
        callback: (status) => {
          if (status) {
            onNext();
          } else {
            Toast.fail(intl.formatMessage({ id: 'PHONE_NUMBER_OR_VERIFICATION_IS_INCORRECT' }));
          }
        },
      });
    }
  }
  useEffect(() => {
    // setTimeout(() => {
    //   setIsWait(true)
    // }, 500)
  }, []);
  useEffect(() => {
    if (isWait) {
      setIndex((vo) => 60);
      // debugger
      time = setInterval(() => {
        // console.log('aaaaaaaaaa')
        setIndex((vo) => {
          if (vo > 0) {
            return vo - 1;
          } else {
            // alert('aaaaaaaa')
            clearInterval(time);
            time = null;
            setIsWait(false);
          }
        });
      }, 1000);
    }
  }, [isWait]);

  const resetData = () => {
    setValue('userName', '');
    setValue('password', '');
    setValue('phone', '');
    setValue('code', '');
    setValue('email', '');
    setValue('password', '');
    setValue('rePassword', '');
  };

  const checkEmail = async () => {
    console.log(email);
    const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
    if (email && emailRegex.test(email)) {
      const res = await checkEmailIsExist(email);
      console.log(res);
      setEmailIsExist(res.data);
    } else {
      Toast.fail(intl.formatMessage({ id: 'PLEASE_ENTER_THE_CORRECT_EMAIL' }), 2);
      return;
    }
  };

  // console.log(index, 'index')
  const intl = useIntl();
  return (
    <div className={styles.box}>
      {/* <div className={styles.header}>
        <img src={step1Img} className={styles.step1}></img>
        <img src={completed} className={styles.completed}></img>
      </div> */}
      {/* {loginType === 1 && (
        <div className={styles.tabWrapper}>
          {tabs.map((item, index) => {
            return (
              <div
                key={index}
                className={`${styles.tabItem} ${
                  loginTypeIndex == index && styles.selectButtonItem
                }`}
                onClick={() => {
                  onChange(index);
                  resetData();
                }}
              >
                <span className={styles.tabTitle}>
                  {getLocale() == 'zh-CN' ? item.name : item.nameEn}
                </span>
              </div>
            );
          })}
        </div>
      )} */}

      <form onSubmit={handleSubmit(onSubmit)}>
        {loginTypeIndex === 0 && loginType === 1 && (
          <div>
            <div className={styles.item}>
              <label className={styles.lable}>{intl.formatMessage({ id: 'USERNAME' })}</label>
              <div className={styles.itemInputBox}>
                <input {...register('userName', { required: true })} autoFocus={focusIndex == 1} />
                <img src={peopleIcon} className={styles.icon} type="number"></img>
              </div>
              {errors.userName && <p>{intl.formatMessage({ id: 'USERNAME' })}</p>}
            </div>
            <div className={styles.item}>
              <label className={styles.lable}>{intl.formatMessage({ id: 'PASSWORD' })}</label>
              <div className={styles.itemInputBox}>
                <input {...register('password', { required: true })} autoFocus={focusIndex == 2} />
              </div>
              {errors.password && <p>{intl.formatMessage({ id: 'PASSWORD' })}</p>}
            </div>
          </div>
        )}
        {loginTypeIndex === 1 && loginType === 1 && (
          <div>
            <div className={styles.item}>
              <label className={styles.lable}>{intl.formatMessage({ id: 'Phone' })}</label>
              <div className={styles.itemInputBox}>
                <input
                  {...register('phone', { required: true })}
                  autoFocus={focusIndex == 1}
                  type="Number"
                />
                <img src={phoneIcon} className={styles.icon} type="number"></img>
              </div>
              {errors.phone && <p>{intl.formatMessage({ id: 'PHONE_NUMBER' })}</p>}
            </div>
            <div className={styles.item}>
              <label className={styles.lable}>
                {intl.formatMessage({ id: 'VERIFICATION_CODE' })}
              </label>
              <div className={styles.itemInputBox}>
                <input {...register('code', { required: true })} autoFocus={focusIndex == 2} />
                <span className={styles.sms} onClick={handleSubmit(getSmsCode)}>
                  {' '}
                  {!isWait ? intl.formatMessage({ id: 'GET_VERIFICATION_CODE' }) : index}
                </span>
              </div>
              {errors.code && <p>{intl.formatMessage({ id: 'VERIFICATION_CODE' })}</p>}
            </div>
          </div>
        )}

        {loginType === 2 && (
          <div>
            <div className={styles.item}>
              <label className={styles.lable}>{intl.formatMessage({ id: 'USER_EMAIL' })}</label>
              <div className={styles.itemInputBox}>
                <input
                  {...register('email', { required: true })}
                  autoFocus={focusIndex == 1}
                  onInput={(e) => {
                    setEmail(e.target.value);
                  }}
                  onBlur={checkEmail}
                />
                <img src={peopleIcon} className={styles.icon} type="number"></img>
              </div>
              {errors.email && <p>{intl.formatMessage({ id: 'USER_EMAIL' })}</p>}
            </div>
            <div className={styles.item}>
              <label className={styles.lable}>{intl.formatMessage({ id: 'PASSWORD' })}</label>
              <div className={styles.itemInputBox}>
                <input {...register('password', { required: true })} autoFocus={focusIndex == 2} />
              </div>
              {errors.password && <p>{intl.formatMessage({ id: 'PASSWORD' })}</p>}
            </div>
            {!emailIsExist && (
              <>
                <div className={styles.rePassword}>{intl.formatMessage({ id: 'REPASSWORD' })}</div>
                <div className={styles.item}>
                  <label className={styles.lable}>
                    {intl.formatMessage({ id: 'CONFIRM_PASSWORD' })}
                  </label>
                  <div className={styles.itemInputBox}>
                    <input
                      {...register('rePassword', { required: true })}
                      autoFocus={focusIndex == 3}
                    />
                  </div>
                  {errors.rePassword && <p>{intl.formatMessage({ id: 'PASSWORD' })}</p>}
                </div>
              </>
            )}
          </div>
        )}

        {loginType === 1 && (
          <div className={styles.tabWrapper}>
            <div
              className={styles.tabItem}
              style={{ color: '#2c589a', marginTop: 100 }}
              onClick={() => {
                setLoginType(2);
                resetData();
              }}
            >
              <span className={styles.tabTitle} style={{ width: 100 }}>
                {getLocale() == 'zh-CN' ? '邮箱登录' : 'Email log in'}
              </span>
            </div>
          </div>
        )}
        {loginType === 2 && (
          <div className={styles.tabWrapper}>
            <div
              className={styles.tabItem}
              style={{ color: '#2c589a' }}
              onClick={() => {
                setLoginType(1);
                resetData();
              }}
            >
              <span className={styles.tabTitle} style={{ width: 100 }}>
                {getLocale() == 'zh-CN' ? '返回' : 'Back'}
              </span>
            </div>
          </div>
        )}
        <button className={styles.button} type="submit" style={{ minHeight: 44 }}>
          {intl.formatMessage({ id: 'LOGIN_BUTTON' })}
        </button>
      </form>
    </div>
  );
}

export default Step1;
